package com.access.boot.apisdk.param.resolve.argument;

import com.access.boot.apisdk.RequestContext;
import com.access.boot.apisdk.annotation.Body;
import com.access.boot.apisdk.exception.MethodArgumentEmptyException;
import com.access.boot.apisdk.param.resolve.HandlerMethodArgumentResolver;
import com.access.boot.apisdk.util.MethodParameter;

/**
 * @author YangZhen
 * @date 2022/6/18 15:59
 * @since 1.0.0
 */
public class RequestBodyMethodArgumentResolver implements HandlerMethodArgumentResolver<RequestContext> {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        if (!parameter.hasParameterAnnotation(Body.class)) {
            return false;
        }
        return true;
    }

    @Override
    public void resolveArgument(RequestContext request, MethodParameter parameter, Object[] arguments) {
        Object argument = arguments[parameter.getParameterIndex()];
        if (argument == null) {
            throw new MethodArgumentEmptyException("Request body for argument of named [" + parameter.getParameterType().getName() + "] can't be empty.");
        }
        request.toRequestBody(argument.toString());
    }
}
